<?php


namespace app\unify\rewrite;


use think\facade\Log;
use think\facade\Queue;

class Event extends \think\Event
{
    public function trigger($event, $params = null, bool $once = false)
    {
        if (!is_array($params) || !isset($params['async'])) {
            //执行原逻辑
            return parent::trigger($event, $params, $once);
        }

        //异步处理

        $async = $params['async'];
        if (is_bool($async)) {
            $async = [
                'delay' => 0,
            ];
        }

        //写入异步队列
        forward_static_call_array(
            [Queue::class, $async['delay'] > 0 ? 'later' : 'push'],
            [
                //指定队列
                'queue' => 'event',
                //指定延时时间
                'delay' => $async['delay'],
                //指定处理类
                'job' => \app\unify\job\Event::class,
                //失败次数超过86400次则直接失败
                'maxTries' => $async['maxTries'] ?? 86400,
                //负载
                'data' => [
                    'event' => $event,
                    'payload' => $params,
                ],
            ]
        );

        //写日志
        Log::info("async[{event}]:{payload}", [
            'event' => $event,
            'payload' => json_encode($params, JSON_UNESCAPED_UNICODE)
        ]);

        return true;
    }
}